package com.example.pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;


import com.example.tests1.SortedListOf;
import com.example.tests1.User;
import com.google.common.collect.Lists;
import static org.junit.Assert.*;

public class UsersPage extends InternalPage {

	@FindBy(name = "username")
	public WebElement usernameFild;

	@FindBy(name = "email")
	public WebElement emailFild;

	@FindBy(id = "password")
	public WebElement passwordFild;

	@FindBy(id = "password2")
	public WebElement password2Fild;
	
	@FindBy(name = "submit")
	public WebElement saveButton;
	
	@FindBy(css = "div#user-list table > tbody > tr")
	public List<WebElement> userRows;

	public UsersPage createUser(User user) {
		usernameFild.sendKeys(user.name);
		emailFild.sendKeys(user.email);
		passwordFild.sendKeys(user.password);
		password2Fild.sendKeys(user.password);
		saveButton.click();
		return MyPageFactory.getPage(driver, UsersPage.class);

	}

	public UsersPage deleteUser(User user) {
		for (WebElement row : userRows) {
			if (user.equals(convertRowToUser(row))) {
				row.findElement(By.xpath("./td[6]/a")).click();
				wait_().until(alertIsPresent()).accept();
				break;
			}
		}
		return MyPageFactory.getPage(driver, UsersPage.class);
	}

	public SortedListOf<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row : userRows) {
			users.add(convertRowToUser(row));
		}
		return new SortedListOf<User>(users);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User().withName(cells.get(1).getText())
				.withEmail(cells.get(2).getText())
				.withRole(cells.get(3).getText());

	}

}
